﻿using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace 畜牧业审核程序国产.Models.ToolsClass
{
    internal class ExpertToExcelHelper
    {
        private static readonly Dictionary<Type, PropertyInfo[]> PropertyCache = new Dictionary<Type, PropertyInfo[]>();

        public static bool ExportToExcel<T>(IEnumerable<T> data ,string pathWithName)
        {
            //// 确保文件路径的目录存在
            //var directory = Path.GetDirectoryName(filePath);
            //if (!Directory.Exists(directory))
            //{
            //    Directory.CreateDirectory(directory);
            //}
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            try
            {
                using (var package = new ExcelPackage())
                {
                    // 添加一个新的工作表
                    var worksheet = package.Workbook.Worksheets.Add("分析数据");

                    // 获取所有公共属性（列名），并缓存
                    var properties = GetCachedProperties(typeof(T));

                    // 写入表头
                    for (int col = 0; col < properties.Length; col++)
                    {
                        worksheet.Cells[1, col + 1].Value = properties[col].Name;
                    }

                    // 写入数据行
                    int rowIndex = 2; // 表头占用了第一行
                    foreach (var item in data)
                    {
                        for (int col = 0; col < properties.Length; col++)
                        {
                            var property = properties[col];
                            var value = property.GetValue(item);

                            // 处理 null 值
                            worksheet.Cells[rowIndex, col + 1].Value = value ?? "N/A";
                        }
                        rowIndex++;
                    }

                    // 自动调整列宽
                    worksheet.Cells.AutoFitColumns();

                    // 保存文件

                    FileInfo file = new FileInfo(Path.Combine(pathWithName));
                    package.SaveAs(file);
                    return true;
                }
            }
            catch (Exception ex)
            {
                StaticLogger.SystemError($"出现错误,错误信息{ex.Message},{Environment.NewLine}堆栈为{ex.StackTrace},{Environment.NewLine}对象为{ex.Source},{Environment.NewLine}方法为{ex.TargetSite}");
                return false;
            }
        }

        private static PropertyInfo[] GetCachedProperties(Type type)
        {
            if (!PropertyCache.TryGetValue(type, out var properties))
            {
                properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
                PropertyCache[type] = properties;
            }
            return properties;
        }
    }
}
